package ntd.util.wx;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import ntd.util.UtilLocal;
import org.w3c.dom.Document;

import java.util.Map;
import java.util.TreeMap;

@Slf4j
public class UtilWx {

    final private static String mch_id = "1603454478"; // 商户号
    final public static String key = "Sf7ydXEWMCmBuCEOG3QI8EHV8pfZ5HAq"; // 商户密钥 - 签名使用
    final private static String notify_url = "https://jiuzhif.com/admin/pay/settlementSuccess"; // 支付回调
    final private static String URL = "https://api.mch.weixin.qq.com/pay/unifiedorder"; // 统一下单接口地址

    /**
     * 统一下单接口
     *
     * @param device_info
     * @param out_trade_no
     * @param total_fee
     * @param openid
     * @return
     */
    public static String unifiedorder(String device_info, String out_trade_no, String total_fee, String openid, String appid) {
        final Map<String, Object> params = new TreeMap();
        params.put("appid", appid);
        params.put("mch_id", mch_id);
        params.put("nonce_str", RandomUtil.randomStringUpper(32));
        if (StrUtil.isNotBlank(device_info)) {
            params.put("device_info", device_info);
        }
        params.put("body", "宋词-酒智付");
        params.put("out_trade_no", out_trade_no);
        params.put("total_fee", total_fee);
        params.put("notify_url", notify_url);
        params.put("trade_type", "JSAPI");
        params.put("openid", openid);
        params.put("spbill_create_ip", UtilLocal.getWebIp());
        params.put("sign", UtilWx.paySign(params, key));
        final Document document = XmlUtil.mapToXml(params, "xml");
        final String post = HttpUtil.post(URL, XmlUtil.toStr(document));
        final Map<String, Object> map = XmlUtil.xmlToMap(post);
        log.info("统一下单-返回：", map);
        if (map.get("return_code").equals("SUCCESS") && map.get("result_code").equals("SUCCESS")) {
            return String.valueOf(map.get("prepay_id"));
        }
        return null;
    }
    /**
     * 微信签名方法
     * @param params
     * @return
     */
    public static String paySign(Map<String, Object> params, String key) {
        StringBuilder stringBuilder = new StringBuilder();
        params.entrySet().forEach(stringObjectEntry -> {
            stringBuilder.append("&");
            stringBuilder.append(stringObjectEntry.getKey());
            stringBuilder.append("=");
            stringBuilder.append(JSONUtil.toJsonStr(stringObjectEntry.getValue()));
        });
        stringBuilder.append("&key=");
        stringBuilder.append(key);
        String string = stringBuilder.toString();
        if (string.startsWith("&")) {
            string = string.substring(1);
        }
        return SecureUtil.md5(string).toUpperCase();
    }
}
